package com.gyms.activity;

import android.app.Activity;
import android.content.Intent;
import android.view.MotionEvent;
import android.view.View;

import com.classic.okhttp.beans.HVProductInfoBean;
import com.classic.okhttp.beans.HVVenueBean;
import com.classic.okhttp.enums.Enum;
import com.classic.okhttp.services.ICommonService;
import com.classic.okhttp.services.IProductService;
import com.classic.okhttp.services.IVenueService;
import com.classic.okhttp.zmoumall.http.ObjectCallback;
import com.classic.okhttp.zmoumall.utils.ToastUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gyms.R;
import com.gyms.base.MyAutoLayoutActivity;
import com.gyms.bean.ThreeWheelBean;
import com.gyms.constant.Constants;
import com.gyms.constant.SpKey;
import com.gyms.manager.LocationManger;
import com.gyms.manager.StateUtils;
import com.gyms.manager.TabManger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import adapter.HistoryAdapter;
import butterknife.BindView;
import constant.EventConstant;
import utils.GsonUtils;
import utils.SPUtil;
import utils.StringUtils;
import weight.SearchView;
import weight.UiEvent;

/**
 * 场馆搜索页面
 * ltx
 */

public class SearchActivity extends MyAutoLayoutActivity implements SearchView.SearchViewListener {

    @BindView(R.id.sv_search)
    SearchView mSvSearch;
    private List<String> mHistory;
    private HistoryAdapter mHistoryAdapter;
    private Gson gson = new Gson();
//    private File mSearchFile;//存储搜索记录的文件
    private String mSearchTabKey;//搜索标签存储的key

    private boolean isGymSearch;

    private String mKeyWord;//搜索关键字

    private TabManger mTabManger;//搜索标签管理类
    //搜索结果页传回的参数
    private int mCurBookType;
    private String mProjectId;
    private String mProjectName;
    private ThreeWheelBean mWheelBean;
    //及时搜索相关
    private String mAreaCode;
    private LocationManger mLocationManger;
    private Enum.EnumVenueListType venueListType;
    private List<String> mRecommendList=new ArrayList<>();

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_search;
    }

    @Override
    protected void initView() {
        createLoadingView(getResources().getString(R.string.str_loading), true);
        initData();
        mSvSearch.setSearchViewListener(this);
        Intent mIntent=getIntent();
        if(null!=mIntent){
            isGymSearch=mIntent.getBooleanExtra(Constants.KEY_IS_GYM_SEARCH,false);
            mKeyWord=mIntent.getStringExtra(Constants.KEY_SEARCH_KEYWORD);
            mSearchTabKey=isGymSearch?SpKey.SP_SEARCH_GYM_TAB:SpKey.SP_SEARCH_PRODUCT_TAB;//初始化存储key
            mCurBookType=mIntent.getIntExtra(Constants.BOOK_TYPE,-1);//当前的预定类型

            //设置默认文案
            mSvSearch.setSearchHint(isGymSearch?"找场馆":"找课程");
            mProjectId = mIntent.getStringExtra(Constants.FLAG_INTENT_PROJECTID);
            mProjectName = mIntent.getStringExtra(Constants.FLAG_INTENT_PROJECTNAME);
            mWheelBean= (ThreeWheelBean) mIntent.getSerializableExtra(Constants.WHEELBEAN_TALG);
        }

        readHistory();
        initHistoryAdapter();
        initKeyWord();
        //初始化标签管理类
        mTabManger=TabManger.getInstance();
        checkIsHaveTagList();
    }

    private void initData() {
        mLocationManger = LocationManger.getInstance(getApplicationContext());
        mAreaCode=mLocationManger.getCityCode();
        venueListType= Enum.EnumVenueListType.All;
    }

    /**
     * 检查内存中是否有搜索标签列表
     * 有的话跳过拉取
     * 没有去网上拉取
     */

    private void checkIsHaveTagList() {
        List<String> mTabLists = isGymSearch ? mTabManger.getGymTabs() : mTabManger.getProductTabs();//场馆搜索 获取场馆标签 否则获取产品标签
        if(StringUtils.isNull(mTabLists)){
            getTagList();
        }else {
            mSvSearch.setSearchTabData(mTabLists);
        }
    }

    /**
     * 获取标签列表
     */

    private void getTagList() {
        loadingView.show();
        ICommonService.getTagList(this, isGymSearch ? Enum.EnumItemType.Field : Enum.EnumItemType.Product, false, new ObjectCallback<ArrayList<String>>() {
            @Override
            public void onSuccess(ArrayList<String> response, String message) {
                dialogDis();
                if (!StringUtils.isNull(response)) {
                    //将TabList设置在内存中
                    if(isGymSearch){
                        mTabManger.setGymTabs(response);
                    }else {
                        mTabManger.setProductTabs(response);
                    }
                    //给流式布局赋值
                    mSvSearch.setSearchTabData(response);
                }
            }

            @Override
            public void onErrorT(int code, ArrayList<String> response, String errorMessage) {
                dialogDis();
            }

            @Override
            public void onHttpErrorCall(int statusCode) {
                dialogDis();
            }
        });
    }

    /**
     * 初始化搜索关键字
     */

    private void initKeyWord() {
        if(!StringUtils.isNull(mKeyWord)){
            mSvSearch.setEtInput(mKeyWord);
        }
    }

    /**
     * 初始化搜索历史列表适配器
     */

    private void initHistoryAdapter() {
        mHistoryAdapter = new HistoryAdapter(getApplicationContext());
        mSvSearch.setHistoryAdapter(mHistoryAdapter);
        mHistoryAdapter.setDataList(mRecommendList);
        if (!StringUtils.isNull(mHistory)&&StringUtils.isNull(mKeyWord)) {//从结果页返回不需要显示历史记录
            mRecommendList.addAll(mHistory);
            mHistoryAdapter.setIsHistory(true);
            mHistoryAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 读取历史搜索数据
     */

    private void readHistory() {
        String strSearchList = (String) SPUtil.get(mContext, isGymSearch?SpKey.SP_SEARCH_GYM_TAB:SpKey.SP_SEARCH_PRODUCT_TAB,"");
        mHistory = gson.fromJson(strSearchList, new TypeToken<List<String>>() {
        }.getType());
        mHistory = mHistory == null ? new ArrayList<String>() : mHistory;
    }

    @Override
    protected void setListener() {
        mSvSearch.setBackmListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        EventBus.getDefault().register(this);
    }

    @Override
    protected void processLogic() {

    }

    @Override
    protected void setTitleTheme() {
        super.setTitleTheme();
    }

    @Override
    public void onRefreshAutoComplete(String text) {
        if(StringUtils.isNull(text)){
            mRecommendList.clear();
            mRecommendList.addAll(mHistory);
            mHistoryAdapter.setIsHistory(true);
            mHistoryAdapter.notifyDataSetChanged();
        }else
        getData(text);
    }

    @Override
    public void onSearch(String keyword) {
        if(StringUtils.isNull(keyword.trim())){
            ToastUtil.showToast(mContext,"请输入关键字");
            return;
        }
        goSearchResult(keyword,Constants.TYPE_KEYWORD);
        boolean isSame = false;//标识是否有相同的
        if (mHistory.size() == 0) {//如果还没有历史数据 直接添加
            mHistory.add(keyword);
        } else {
            for (int i = 0; i < mHistory.size(); i++) {//遍历现有的list移除相同的，并重新添加
                if (keyword.equals(mHistory.get(i))) {//如果有相同的移除 再重新add
                    mHistory.remove(i);
                    mHistory.add(0, keyword);
                    isSame = true;
                    break;
                } else {
                    isSame = false;
                }
            }
            if (!isSame) {
                if (mHistory.size() == 3) {//最多只有三个 如果满三个移除第三项
                    mHistory.remove(2);
                    mHistory.add(0, keyword);
                } else {//不满第三项直接添加
                    mHistory.add(0, keyword);
                }
            }
        }
        //刷新列表
        mRecommendList.clear();
        mRecommendList.addAll(mHistory);
        mHistoryAdapter.setIsHistory(true);
        mHistoryAdapter.notifyDataSetChanged();
    }

    /**
     * 去搜索结果页面
     * @param keyword 搜索关键字
     * @param type 搜索类型 分为 关键字搜索 和标签搜索
     */

    private void goSearchResult(String keyword,int type) {
        Intent intent = new Intent(mContext, SearchResultActivity.class);
        intent.putExtra(Constants.BOOK_TYPE,mCurBookType);
        intent.putExtra(Constants.KEY_SEARCH_TYPE,type);
        intent.putExtra(Constants.KEY_SEARCH_KEYWORD,keyword);
        intent.putExtra(Constants.KEY_IS_GYM_SEARCH,isGymSearch);

        intent.putExtra(Constants.WHEELBEAN_TALG,mWheelBean);

        intent.putExtra(Constants.FLAG_INTENT_PROJECTID, mProjectId);//id
        intent.putExtra(Constants.FLAG_INTENT_PROJECTNAME, mProjectName);//name
        startActivity(intent);
        ((Activity) mContext).overridePendingTransition(0, 0);//去除默认系统动画
        finish();
    }

    @Override
    protected void onPause() {
        String mHistoryJson= GsonUtils.toJson(mHistory);
        SPUtil.put(mContext,mSearchTabKey,mHistoryJson);
        super.onPause();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        hideKeyBoard(ev);//隐藏软键盘
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    //标签点击的回调  返回对象
    @Subscribe
    public void getTabCall(UiEvent mUiEvent){
        String mKey=mUiEvent.getKey();
        if(EventConstant.FLAG_TAB_CALL.equals(mKey)){
            String mTabObj= (String) mUiEvent.getObject();
            goSearchResult(mTabObj,Constants.TYPE_TAB);
        }
    }

    /**
     * 获取场馆数据或者获取产品数据
     *
     */

    private void getData(String mKeyWord) {
        if (isGymSearch) {//获取场馆列表
            getVenueList(mKeyWord);
        } else {//获取产品列表
            getProductList(mKeyWord);
        }
    }

    /**
     * 根据搜索关键字获取内容
     *
     */
    private void getVenueList(String mKeyWord) {
        IVenueService.getVenueList(this, mAreaCode, mLocationManger.longitude, mLocationManger.latitude, null, null, null, mKeyWord, mPageIndex, PAGESIZE, venueListType, null,null,true, new ObjectCallback<ArrayList<HVVenueBean>>() {
            @Override
            public void onHttpErrorCall(int statusCode) {
            }

            @Override
            public void onSuccess(ArrayList<HVVenueBean> response, String message) {
                mRecommendList.clear();
                if(!StringUtils.isNull(response)){
                    mRecommendList.addAll(StateUtils.doGetSearchGymName(response,isGymSearch));
                    mHistoryAdapter.setIsHistory(false);
                }
                mHistoryAdapter.notifyDataSetChanged();
            }

            @Override
            public void onErrorT(int code, ArrayList<HVVenueBean> response, String errorMessage) {
            }
        });
    }


    /**
     * 根据搜索关键字获取内容
     *
     */
    private void getProductList(String mKeyWord) {
        IProductService.getProductList(this, mAreaCode, mLocationManger.longitude, mLocationManger.latitude, mKeyWord, mPageIndex, PAGESIZE, null, null,false, new ObjectCallback<ArrayList<HVProductInfoBean>>() {
            @Override
            public void onHttpErrorCall(int statusCode) {
            }

            @Override
            public void onSuccess(ArrayList<HVProductInfoBean> response, String message) {
                mRecommendList.clear();
                if(!StringUtils.isNull(response)){
                    mRecommendList.addAll(StateUtils.doGetSearchGymName(response,isGymSearch));
                    mHistoryAdapter.setIsHistory(false);
                }
                mHistoryAdapter.notifyDataSetChanged();
            }

            @Override
            public void onErrorT(int code, ArrayList<HVProductInfoBean> response, String errorMessage) {
            }
        });
    }

}
